import axios from 'axios';
import qs from 'qs';
import router from '../router/index';
import {Message} from 'iview';
import {loginRouter} from "../router/router";
import Cookies from "js-cookie";

axios.defaults.timeout = 10000;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest';
// axios.defaults.baseURL = ajaxUrl;
axios.defaults.responseType = 'json';
// axios.defaults.withCredentials = true;

axios.interceptors.request.use((config) => {
  if (config.method === 'post') {
    if (config.headers['Content-Type'] == 'application/x-www-form-urlencoded;charset=UTF-8') {
      config.data = qs.stringify(config.data);
    }
    // config.data = qs.stringify(config.data);
    // config.headers['Content-Type'] ='application/json;charset=UTF-8';
  }
  if (window.localStorage.getItem('token')) { // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers['token'] = window.localStorage.getItem('token');
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

// code状态码200判断
axios.interceptors.response.use((res) => {
  if (res.data && res.data.code === 0) {
    if (res.data.message === '无效的token' || res.data.message === 'token为空') {

      Cookies.remove('user');
      Cookies.remove('password');
      Cookies.remove('access');
      Cookies.remove('setThirdToken');
      Cookies.remove('fp_smartwork_token');
      Cookies.remove('fp_uacid');
      setTimeout(function () {
        router.replace({
          path: '/login',
          query: {redirectUrl: router.currentRoute.name, access: router.currentRoute.meta.flags},
        })
      }, 1000);
      if (localStorage.getItem('token')) {
        Message.error('登录过期，请重新登录');
        window.localStorage.removeItem('token');
        window.localStorage.removeItem('userId');
        window.localStorage.removeItem('username');
      }
      return false;
    } else {
      Message.error({content: res.data.message, duration: 3});
      return false;
    }
  }
  if (res.data && res.data.code === -1) {
    Message.error(res.data.message);
    return false;
  }
  return res;
}, (error) => {
  console.log('网络异常');

  if (error && error.response) {
    switch (parseInt(error.response.status)) {
      case 401:
        setTimeout(function () {
          router.replace({
            path: '/login',
            query: {redirectUrl: router.currentRoute.name}
          });
        }, 1000);
        window.localStorage.removeItem('token');
        error.message = '登录过期，请重新登录';
        break;
      case 504:
        error.message = '网关超时';
        break;
      case 502:
        error.message = '后端接口未开';
        break;
      case 403:
        error.message = '当前账号没有操作权限';
        break;
    }
  } else {
    error.message = String(error);
    Message.error(error.message);
    return false
  }
  return Promise.reject(error);
});

export default axios;
